Medium
Given a multi-dimensional array arr
and a depth n
, return a flattened version of that array.
A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n
. The depth of the elements in the first array are considered to be 0
.
Please solve it without the built-in Array.flat
method.
給定多維陣列 arr
和深度 n
,回傳該陣列的扁平化後的版本。
多維陣列是包含整數或其他多維陣列的遞歸資料結構。
扁平化陣列是參數陣列在刪除部分或全部子陣列並替換為該子陣列中的實際元素的版本。
Input
arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 0
Output
[1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
僅在當前嵌套深度小於 n
時才應執行此展平操作。
第一個陣列中元素的深度被視為0
。
請在沒有內建Array.flat
方法的情況下解決它。
var flat = function (arr, n) {
let answer = [];
// 展平邏輯
// 使用for迴圈遍歷多維陣列`arr`,
// 判斷要進行遞迴還是元素放進`answer陣列`
for(let i=0; i<arr.length; i++){
if(n>0 && Array.isArray(arr[i])){
//遞迴邏輯處理:
// ✓ 遞迴函式
// 目前處理的元素 arr[i] 作為參數傳遞給 flat 函數,
// 同時將深度 n 減一。
// ✓ 展開運算符...
// 將 flat(arr[i], n-1) 的結果展開為一系列的元素,
// 並將它們添加到 answer 陣列中。
answer.push(...flat(arr[i], n-1));
}
else{ answer.push(arr[i]);}
}
return answer;
};
let arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]];
let n = 0;
console.log(JSON.stringify(flat(arr,n)));
//Output: [1,2,3,[4,5,6],[7,8,[9,10,11],12],[13,14,15]]
arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 1
console.log(JSON.stringify(flat(arr,n)));
//Output: [1,2,3,4,5,6,7,8,[9,10,11],12,13,14,15]
arr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 2
console.log(JSON.stringify(flat(arr,n)));
//Output: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]